/* 引入依赖 */
const express = require("express");
const expressIp = require('express-ip');
const bodyParser = require('body-parser')
const cors = require('cors');
const initDB = require('./db/init')
initDB()
const expressJwt = require('express-jwt')
const SECRET_KEY = 'hannz'
const errorhandler = require('./middleware/errorhandler')
var morgan = require('morgan');
var fs = require('fs');
var path = require('path');
// 日志
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });

/* 创建express实例 */
const app = express();
app.use(cors())

app.use(bodyParser.urlencoded({     //使用body-parser中间件
    extended: false
}))
app.use(bodyParser.json())// 指定post请求的数据为json数据

app.use(expressIp().getIpInfoMiddleware);
app.use(morgan('short', { stream: accessLogStream }));
require("./swagger")(app);
app.use(express.static(__dirname))
app.use(expressJwt({
    secret: SECRET_KEY,
    algorithms: ['HS256'], // 使用何种加密算法解析
}).unless({ path: ['/api/user/login', '/api/user/register','/uploads'] }) // 登录页无需校验
)

// const perdetailRouter =require('./routes/perdetail');
const cateRouter = require('./routes/cate')
const userRouter = require('./routes/login')
const articleRouter = require('./routes/article')
const fileRouter = require('./routes/flie')
app.use('/api/cate', cateRouter)
app.use('/api/user', userRouter)
app.use('/api/article', articleRouter)
app.use('/api/file', fileRouter)
// 使用中间件处理error
app.use(errorhandler)

// 绑定服务端口，启动服务器
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});

/* 定义路由接口 */
app.get("/", (req, res) => {
    res.send("Hello Express");
});
app.listen(5000, () => console.log('Server listening on port 5000!'))
